#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
数据库迁移执行脚本
"""

import pymysql
import sys
import os
from config import Config

def run_migration(sql_file_path):
    """执行数据库迁移脚本"""
    try:
        # 读取SQL文件
        with open(sql_file_path, 'r', encoding='utf-8') as f:
            sql_content = f.read()
        
        # 连接数据库
        connection = pymysql.connect(
            host=Config.DB_HOST,
            port=Config.DB_PORT,
            user=Config.DB_USER,
            password=Config.DB_PASSWORD,
            database=Config.DB_NAME,
            charset='utf8mb4'
        )
        
        try:
            with connection.cursor() as cursor:
                # 分割SQL语句（按分号分割，忽略注释）
                sql_statements = []
                current_statement = ""
                
                for line in sql_content.split('\n'):
                    line = line.strip()
                    # 跳过注释和空行
                    if line.startswith('--') or not line:
                        continue
                    
                    current_statement += line + " "
                    
                    # 如果行以分号结尾，表示一个完整的SQL语句
                    if line.endswith(';'):
                        sql_statements.append(current_statement.strip())
                        current_statement = ""
                
                # 执行每个SQL语句
                for sql in sql_statements:
                    if sql.strip():
                        print(f"执行SQL: {sql[:50]}...")
                        cursor.execute(sql)
                
                # 提交事务
                connection.commit()
                print("✅ 数据库迁移执行成功！")
                
        finally:
            connection.close()
            
    except Exception as e:
        print(f"❌ 数据库迁移执行失败: {str(e)}")
        sys.exit(1)

if __name__ == '__main__':
    if len(sys.argv) != 2:
        print("用法: python run_migration.py <sql_file_path>")
        sys.exit(1)
    
    sql_file = sys.argv[1]
    if not os.path.exists(sql_file):
        print(f"❌ SQL文件不存在: {sql_file}")
        sys.exit(1)
    
    print(f"🚀 开始执行数据库迁移: {sql_file}")
    run_migration(sql_file)